class Solution
{
public:
    int scheduleCourse(vector<vector<int>> &courses)
    {
        sort(courses.begin(), courses.end(), [](auto &c1, auto &c2)
             { return c1[1] < c2[1]; });

        int cur = 0;
        int count = 0;
        priority_queue<int> pq;
        for (auto &c : courses)
        {
            if (cur + c[0] <= c[1])
            {
                cur += c[0];
                ++count;
                pq.push(c[0]);
            }
            else if (!pq.empty() && pq.top() > c[0])
            {
                cur = cur + c[0] - pq.top();
                pq.pop();
                pq.push(c[0]);
            }
        }
        return count;
    }
};